/**
 * 
 */
package com.czmh.etc.onlinepubsys.services.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.czmh.etc.onlinepubsys.dto.EtcAddressbookDto;
import com.czmh.etc.onlinepubsys.dto.EtcApplyDto;
import com.czmh.etc.onlinepubsys.dto.EtcIdcardDto;
import com.czmh.etc.onlinepubsys.dto.EtcVehiclelicenseDto;
import com.czmh.etc.onlinepubsys.exceptions.EtcMsgException;
import com.czmh.etc.onlinepubsys.feign.newrun.DianApplyClient;
import com.czmh.etc.onlinepubsys.feign.newrun.entity.yunnan.EtcYnApplyInfo;
import com.czmh.etc.onlinepubsys.feign.newrun.entity.yunnan.EtcYnApplyInfoVO;
import com.czmh.etc.onlinepubsys.feign.newrun.entity.yunnan.EtcYnCarInfo;
import com.czmh.etc.onlinepubsys.feign.newrun.entity.yunnan.EtcYnShippingInfo;
import com.czmh.etc.onlinepubsys.json.JsonResult;
import com.czmh.etc.onlinepubsys.maper.EtcApplyMapper;
import com.czmh.etc.onlinepubsys.model.EtcApply;
import com.czmh.etc.onlinepubsys.services.DianService;
import com.czmh.etc.onlinepubsys.services.EtcOrderService;
import com.czmh.etc.onlinepubsys.services.EtcUserInfoSevice;
import com.czmh.etc.onlinepubsys.utils.JsonResultUtil;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;

import feign.RetryableException;
import lombok.extern.slf4j.Slf4j;

/**
 * @描述：
 * @author： Seven.
 * @创建日期：Nov 1, 2019 3:46:45 PM.
 * @版本：1.0.0
 */
@Service
@Transactional(noRollbackFor = Exception.class)
@Slf4j
public class DianServiceImpl implements DianService {
    @Autowired
    private DianApplyClient dianApplyClient;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private EtcApplyMapper etcApplyMapper;
    @Autowired
    private EtcUserInfoSevice etcUserInfoSevice;
    @Autowired
    private EtcOrderService etcOrderService;
    
    @Value("${etc.ynMiniRedirect}")
    private String ynMiniRedirect;
    
    @Override
    public JsonResult loginByWx(String channelId, String code, String openId) {
        return dianApplyClient.loginByWx(channelId, code, openId);
    }

    @Override
    public JsonResult obuapply() {
        return dianApplyClient.obuapply();
    }

    @Override
    public JsonResult saveYnApplyInfo(EtcYnApplyInfoVO saveApplyReqDTO) {
        // 申办的卡类型
        String catId = saveApplyReqDTO.getCatId();
        EtcYnApplyInfo applyInfo = saveApplyReqDTO.getEtcYnApplyInfo();
        EtcYnCarInfo carInfo = saveApplyReqDTO.getEtcYnCarInfo();
     // 1.封装申请信息
        EtcApplyDto apply = new EtcApplyDto();
        // 设置申办渠道
        apply.setApply_channel(StringUtils.isEmpty(applyInfo.getApply_channel()) ? 1 : Integer.valueOf(applyInfo.getApply_channel()));
        apply.setApply_carlicencetyoe("0");
        // 设置车牌号码
        apply.setApply_carlicence(carInfo.getLicencePlate());
        apply.setApply_name(applyInfo.getApplyInfoName());
        apply.setApply_idcard(applyInfo.getIdCard());
        apply.setApply_carowneridcardfrontalphoto(applyInfo.getIdCardRightImg());
        apply.setApply_carowneridcardreversephoto(applyInfo.getIdCardWrongImg());
        apply.setApply_drivinglicencefrontalphoto(carInfo.getDrivingPermiRightImg());
        apply.setApply_drivinglicencereversephoto(carInfo.getDrivingPermiWrongImg());
        apply.setApply_carheadphoto(carInfo.getCarHeader45Img());
        apply.setApply_mannednum(String.valueOf(carInfo.getHostNumberApproved()));
        apply.setCardCatId(catId);
        apply.setApply_creditcard(applyInfo.getApply_creditcard());
        apply.setSerialnum(applyInfo.getSerialnum());
        apply.setUser_id(saveApplyReqDTO.getUserId());
        // 2.封装用户身份证信息
        EtcIdcardDto idcard = new EtcIdcardDto();
        idcard.setAddress(applyInfo.getAddress());
        idcard.setNum(applyInfo.getIdCard());
//        idcard.setEnd_date(DatetimeUtil.formatDate(applyInfo.getIdExpDate()));
//        idcard.setStart_date(DatetimeUtil.formatDate(applyInfo.getIdEffDate()));
        idcard.setName(applyInfo.getApplyInfoName());
        // 3.封装行驶证信息
        EtcVehiclelicenseDto vehiclelicense = new EtcVehiclelicenseDto();
        vehiclelicense.setPlate_num(carInfo.getLicencePlate());
        vehiclelicense.setVehicle_type(carInfo.getCarType());
        vehiclelicense.setOwner(carInfo.getCarOwner());
        vehiclelicense.setUse_character(String.valueOf(carInfo.getCarUseType()));
        vehiclelicense.setModel(carInfo.getCarBrand());
        vehiclelicense.setVin(carInfo.getVin());
        vehiclelicense.setEngine_num(carInfo.getEngineNo());
        vehiclelicense.setRegister_date(carInfo.getRegisterDate());
        vehiclelicense.setIssue_date(carInfo.getIssueDate());
        vehiclelicense.setAppproved_passenger_capacity(String.valueOf(carInfo.getHostNumberApproved()));;
        vehiclelicense.setFile_no(carInfo.getVehicleFrameNo());
        vehiclelicense.setOverall_dimension(carInfo.getCarLength() + "X" + carInfo.getCarWidth() + "X" + carInfo.getCarHeight());
        vehiclelicense.setGross_mass(carInfo.getTotalWeight());
        vehiclelicense.setInspection_record("");
        vehiclelicense.setAddr(applyInfo.getAddress());
        EtcApply submitApplyInfo = etcUserInfoSevice.submitApplyInfo(saveApplyReqDTO.getUserId(), apply, idcard, vehiclelicense);
        Map<String, String> map = new HashMap<>();
        map.put("applyId", submitApplyInfo.getApply_id());
        // 调用纽润接口
        saveApplyReqDTO.setUserId(null);
        JsonResult jsonResult = null;
        try {
            jsonResult = dianApplyClient.saveYnApplyInfo(saveApplyReqDTO);
        } catch (RetryableException e) {
            log.error("保存云南发行申请异常：", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
       
        if (!JsonResult.CODE_SUCCESS.equals(jsonResult.getCode().toString())) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new EtcMsgException(jsonResult.getCode(), jsonResult.getMessage());
        } else {
            Map<String, Object> toMap = (HashMap<String, Object>) jsonResult.getData();
            String niurunApplyId = toMap.get("applyId").toString();
            map.put("niurunApplyId", niurunApplyId);
            EtcApply update = new EtcApply(submitApplyInfo.getApply_id());
            update.setNiurunApplyId(niurunApplyId);
            etcApplyMapper.update(update);
            return JsonResultUtil.toResult(map);
        }
    }

    @Override
    public JsonResult banksign(String applyId, String bankId, String miniRedirect, String userPhone) {
        if (StringUtils.isEmpty(miniRedirect)) {
            miniRedirect = ynMiniRedirect;
        }
        return dianApplyClient.banksign(applyId, bankId, miniRedirect, userPhone);
    }

    @Override
    public JsonResult addShippingInfo(EtcYnShippingInfo shippingInfo) {
        EtcAddressbookDto addressbookDto = new EtcAddressbookDto();
        addressbookDto.setUser_id(shippingInfo.getLoginUserId());
        addressbookDto.setApply_id(shippingInfo.getApplyId());
        addressbookDto.setAd_consignee(shippingInfo.getShippingName());
        addressbookDto.setAd_consigneephone(shippingInfo.getShippingMobile());
        addressbookDto.setAd_province(shippingInfo.getShippingProvince());
        addressbookDto.setAd_city(shippingInfo.getShippingCity());
        addressbookDto.setAd_region(shippingInfo.getShippingArea());
        addressbookDto.setAd_detailaddress(shippingInfo.getShippingAddress());
        String orderId = etcOrderService.submitaddrOrder(addressbookDto, "dian");
        Map<String, String> map = new HashMap<String, String>();
        map.put("orderId", orderId);
        JsonResult jsonResult = dianApplyClient.addShippingInfo(shippingInfo);
        if (!JsonResult.CODE_SUCCESS.equals(jsonResult.getCode().toString())) {
            throw new EtcMsgException(jsonResult.getCode(), jsonResult.getMessage());
        } else {
            return JsonResultUtil.toResult(map);
        }
    }

    @Override
    public JsonResult changeStatus(String applyId) {
        EtcApply etcApply = etcApplyMapper.getById(applyId);
        if (etcApply != null) {
            EtcApply update = new EtcApply(applyId);
            update.setApply_status(8);
            etcApplyMapper.update(update);
            JsonResult jsonResult = dianApplyClient.changeStatus(etcApply.getNiurunApplyId());
            if (!JsonResult.CODE_SUCCESS.equals(jsonResult.getCode().toString())) {
                throw new EtcMsgException(jsonResult.getCode(), jsonResult.getMessage());
            } else {
                return jsonResult;
            }
        } else {
            throw new EtcMsgException(1, "申请信息不存在！");
        }
    }

}
